package org.ithang.lock;

import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;
/**
 * 售票示例，采用lock类，即ReentrantLock
 * @author Administrator
 *
 */
public class ThreadLockTest2 {

	
	private int count=100;
	
	
	
	/**
	 * lock.lock(); 去加锁，直到加锁成功
		lock.lockInterruptibly();//去加锁，如果不成功则等待，在等待的过程中，可以被中断
		lock.tryLock();//尝试加锁，如果不成功，则不再尝试
		lock.tryLock(60, TimeUnit.SECONDS);//在指定时间内尝试加锁，如果未成功，则不在尝试
		lock.newCondition();//根据某个条件判断是否要加锁
	 */
	private ReentrantLock lock=new ReentrantLock();
	
	@Test
	public void ticketTest(){
		
		new Thread(()->sell(),"1号售票员").start();
		new Thread(()->sell(),"2号售票员").start();
		new Thread(()->sell(),"3号售票员").start();
		
		try{
		    Thread.sleep(50000);
		}catch(Exception e){}
	}
	
	
	private void sell(){
		while(count>0){
			try{
			lock.lock();
			    System.out.println(Thread.currentThread().getName()+" 卖出第"+count+"张票");
			    count--;
			    Thread.sleep(800);
			}catch(Exception e){}
			finally{
				lock.unlock();
			}
			
		}
	}
	
	
}
